

#import "HttpEngine.h"

@implementation HttpEngine

-(void) postDataToServer:(NSString*) relativeUrl param:(NSMutableDictionary*) params andFile:(NSMutableDictionary*) file onCompletion:(ResponseSuccessBlock) responseSuccess onError:(ResponseErrorBlock) responseError {
    
    MKNetworkOperation *networkOperation = [self operationWithPath:relativeUrl params:params httpMethod:@"POST"];
    if (file!=nil&&[file isKindOfClass:[NSDictionary class]]) {
        id values=[file objectForKey:@"data"];
        if ([values isKindOfClass:[NSData class]]) {
            if (nil==[file objectForKey:@"filename"]) {
                [networkOperation addData:values forKey:[file objectForKey:@"name"]];
                DLog(@"当上传图片为NSData类型时请传入文件名字！");
            }else{
            [networkOperation addData:values forKey:[file objectForKey:@"name"] mimeType:@"application/octet-stream" fileName:[file objectForKey:@"filename"]];
            }
        }else if([values isKindOfClass:[NSString class]]){
            [networkOperation addFile:values forKey:[file objectForKey:@"name"] mimeType:@"application/octet-stream"];
            }
    // setFreezable uploads your images after connection is restored!
    [networkOperation setFreezable:YES];
    }
    [networkOperation onCompletion:^(MKNetworkOperation *completedOperation) {
        if (completedOperation.HTTPStatusCode>=200&&completedOperation.HTTPStatusCode<500) {
            id response = [completedOperation responseJSON];
            if ([response isKindOfClass:[NSString class]]) {
                 NSLog(@"%@",@"IOS5以下请自己解析json字符串");
            }else{
                 responseSuccess(response);
            }
            responseSuccess(response);
        }else{
            responseError([NSString stringWithFormat:@"服务器异常,%d",completedOperation.HTTPStatusCode]);
        }
    } onError:^(NSError *error) {
        NSString *msg;
        switch (error.code) {
            case 503:
                msg=@"服务器无响应";
                break;
            case 504:
                msg=@"服务器响应超时";
                break;
            default:
                msg=@"服务器异常";
                break;
        }
        responseError([NSString stringWithFormat:@"%@;%@",msg,error.localizedDescription]);
    }];
    
    [self enqueueOperation:networkOperation];
}



@end
